package com.xt.core.helper;

import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MapValueFactory{
	
	/**
	 * get unsorted map
	 * 
	 * @param soureStr the value string
	 * @return
	 */
	public static HashMap<String, String> formatList(String soureStr){
		HashMap<String, String> results = new HashMap<String, String>();		
		try{
			StringTokenizer st = new StringTokenizer(soureStr, ";");
			StringTokenizer st2;
			while (st.hasMoreTokens()) {
				try{
					String tempStr = st.nextToken();
					System.out.println("token: " + tempStr);
					String value;
					String name;
					if(tempStr.indexOf("|")!=-1){
						st2 = new StringTokenizer(tempStr, "|");
						value = st2.nextToken();
						name = st2.nextToken();
					}else{
						System.out.println("take both!");
						value = tempStr;
						name = tempStr;
					}
					//String[] strToken = tempStr.split("|");
					//System.out.println(tempStr + ": " +  strToken[0] + " - " + strToken[1] );
					//results.add(new MapValue(strToken[1],strToken[0]));
					//System.out.println(tempStr + ": " +  value + " - " + name );
					results.put(value,name);
				}catch(Exception e){
					e.printStackTrace();
					continue;
				}
		    }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return results;
	}
	
	/**
	 * get sorted map values
	 * @param soureStr the soure string
	 * @return
	 */
	public static TreeMap<String, String> formatMapValues(String soureStr){
		TreeMap<String, String> results = new TreeMap<String, String>(new StrComparator());	

		try{
			StringTokenizer st = new StringTokenizer(soureStr, ";");
			StringTokenizer st2;
			while (st.hasMoreTokens()) {
				try{
					String tempStr = st.nextToken();
					String value;
					String name;
					if(tempStr.indexOf("|")!=-1){
						st2 = new StringTokenizer(tempStr, "|");
						name = st2.nextToken();
						value = st2.nextToken();
					}else{
						name = tempStr;
						value = tempStr;
					}
					
					results.put(value, name);
				}catch(Exception e){
					e.printStackTrace();
					continue;
				}
		    }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return results;
	}	
}
